// eslint-disable-next-line
import { useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";
import Creator from "../store/actions";
import AddressApi from '../api/address';

export const useAddress = () => {
    // 提取数据
    const address = useSelector(state => state.address);
    // 提取数据  useSelector共享状态,从Redux的store中提取数据
    const oneAddr = useSelector(state => state.oneAddr);
    const dispatch = useDispatch();
    const { curPage, eachPage } = address

    // 操作状态的行为
    const getAddress = useCallback(async () => {
        const data = await AddressApi.get({ curPage, eachPage })
        dispatch(Creator.getAddress(data));
    }, [curPage, eachPage, dispatch]);

    // 拿到当前页
    const setCurPage = useCallback(curPage => {
        dispatch(Creator.setCurPage(curPage));
    }, [dispatch])

    // 更新显示条数
    const setEachPage = useCallback(eachPage => {
        dispatch(Creator.setEachPage(eachPage));
    }, [dispatch])

    //修改数据
    // useCallback性能优化
    const amendAdderss = useCallback(async ({ name, address, phone, Open_hours, longitude, latitude, _id }) => {
        // 通过调用api拿到需要修改的所有数据
        return await AddressApi.amend({ name, address, phone, Open_hours, longitude, latitude, _id })
    }, [])

    // 获取_id对应自提点的数据
    const getOneAddress = useCallback(async _id => {
        const data = await AddressApi.getOne({ _id })
        dispatch(Creator.getOneAddress({ data }))
    }, [dispatch])

    // 搜索数据
    const searchAddr = useCallback(async name => {
        // 通过name去查询数据
        const data = await AddressApi.getsearch(name)
        // 通过payload解构拿到data
        console.log(data);
        dispatch(Creator.searchAddress({ data }))
    }, [dispatch])

    // 删除图片
    const removeImg = useCallback(async ({ _id, url }) => {
        console.log(url);
        return await AddressApi.removeImg({ _id, url })
    }, [])

    return [{ address, oneAddr }, { getAddress, setCurPage, setEachPage, amendAdderss, getOneAddress, searchAddr, removeImg }]
}